﻿using Microsoft.Research.DynamicDataDisplay;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace NB_Controller_Test
{    
    public partial class MainUIEx : UserControl
    {
        private ObservableCollection<Tuple<int, string, string>> eventLogList = new ObservableCollection<Tuple<int, string, string>>();

        private List<EventLog> eventLogs = new List<EventLog>();

        private delegate void DelAddNewItemByEventLog(EventLog eventLog);

        public class ExcelSheet
        {
            public string strSheetName;
            public DataTable dataTable;// = new DataTable();

            public ExcelSheet()
            {
                strSheetName = "";

                dataTable = new DataTable();
                dataTable.Columns.Add(new DataColumn("^UID", typeof(string)));
                dataTable.Columns.Add(new DataColumn("^DeviceID", typeof(string)));
                dataTable.Columns.Add(new DataColumn("^报文类型", typeof(string)));
                dataTable.Columns.Add(new DataColumn("^时间", typeof(string)));
                dataTable.Columns.Add(new DataColumn("^cmdId", typeof(string)));
                dataTable.Columns.Add(new DataColumn("^内容", typeof(string)));
            }
        };

        private List<ExcelSheet> excelSheetList = new List<ExcelSheet>();

        public void InitEventLog()
        {
            this.timeline.ItemsSource = eventLogList;
        }

        public void AddNewItem(E_EventType type, string strTime, string strInfo)
        {
            eventLogList.Add(new Tuple<int, string, string>(Convert.ToInt32(type), "[" + (eventLogList.Count + 1).ToString() + "] " + strTime, strInfo));
        }

        public void AddNewItemByEventLog(EventLog eventLog)
        {
            //存储解析后的eventlog
            eventLogs.Add(eventLog);

            string strPredictTime = "[预估]";
            if(eventLog.bPredictTime == false)
                strPredictTime = "[可信]";

            strPredictTime += (" LogID[" + eventLog.usLogID.ToString() + "]");
            strPredictTime += (" EventID[" + eventLog.byEventID.ToString() + "]");
            
            string strDateAndTime = "20" + eventLog.strDate + string.Format(" {0}:{1}:{2}", eventLog.byHour, eventLog.byMin, eventLog.bySecond);
            string strInfo = "{" + eventLog.strOriLogData + " -> " + eventLog.strHexOriLogData + "}\r\n" + eventLog.strAnalyData + "\r\n" + eventLog.strEventParamInfo;
            eventLogList.Add(new Tuple<int, string, string>(
                (Int32)eventLog.eventType, 
                "[" + (eventLogList.Count + 1).ToString() + "] " + strDateAndTime + strPredictTime + " 事件--[" + eventLog.strEventIDInfo + "]", 
                strInfo));
            //逆序插入
            //eventLogList.Insert(0, new Tuple<int, string, string>((Int32)eventLog.eventType, "[" + (eventLogList.Count + 1).ToString() + "] " + strDateAndTime + strPredictTime + " [" + eventLog.strEventIDInfo + "]", strInfo));
        }

        private void but_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.Source as Button;
            switch (btn.Tag.ToString())
            {
                case "ReadWifiLog":
                    {
                        Microsoft.Win32.OpenFileDialog openDlg = new Microsoft.Win32.OpenFileDialog();
                        openDlg.DefaultExt = ".txt";
                        openDlg.Filter = "Txt文档|*.txt|所有文件|*.*";
                        if (openDlg.ShowDialog() == true)
                        {
                            string strFilePath = openDlg.FileName;
                            string strAllText = System.IO.File.ReadAllText(strFilePath, Encoding.UTF8);

                            AnalysisWifiLogs(strAllText);
                        }
                    }
                    break;
                case "ReadZKLog":
                    {
                        Microsoft.Win32.OpenFileDialog openDlg = new Microsoft.Win32.OpenFileDialog();
                        //openDlg.DefaultExt = ".xlsx";
                        openDlg.Filter = "xls files (*.xls)|*.xls|xlsx files (*.xlsx)|*.xlsx|所有文件|*.*";
                        if (openDlg.ShowDialog() == true)
                        {
                            string strFilePath = openDlg.FileName;
                            //string strAllText = System.IO.File.ReadAllText(strFilePath, Encoding.UTF8);
                            //AnalysisWifiLogs(strAllText);                            

                            excelSheetList.Clear();
                            GlobalFun.ReadExcelForeachSheets(excelSheetList, strFilePath, 2 );

                            AnalysisZKLogs(excelSheetList);
                        }
                    }
                    break;
                case "AnisalyError":
                    {

                    }
                    break;
                case "ReadPostmanLog":
                    AddNewItem(E_EventType.Info, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "信息事件[M]");
                    break;
                case "ReadJSon":
                    {
                        try
                        {
                            //获取到纯JSon数据
                            string strJsonTemp = tbRecvMsgData.Text;
                            if(strJsonTemp.Contains("BE BE BE BE"))
                            {
                                //是Wifi读取到的结果
                                AnalysisWifiLogs(strJsonTemp);
                            }
                            else
                            {
                                JObject jObj = JObject.Parse(strJsonTemp);
                                //除去多余无效\r\n以及空格
                                //strContentData = jObj.ToString();
                                strJsonTemp = jObj.ToString().Replace("\r\n ", "");
                                strJsonTemp = strJsonTemp.Replace("  ", "");
                                //System.Diagnostics.Debug.WriteLine(strJsonTemp);

                                //构建Log
                                List<EventLog> eventLogsLocal = EventLogManager.MakeEventLog(jObj);
                                foreach (EventLog eventLog in eventLogsLocal)
                                {
                                    //eventLog.strLogIP = strIP;

                                    //增加节点
                                    AddNewItemByEventLog(eventLog);
                                }
                            }                            
                        }
                        catch (Newtonsoft.Json.JsonReaderException jsonEx)
                        {
                            string strError = jsonEx.Message;
                            //提取出有效信息，格式化为中文描述
                            string strTrueError = strError.Substring(strError.IndexOf("Path "));
                            string[] strLst = strTrueError.Split(',');

                            string strKeyName = strLst[0].Trim().Substring(strLst[0].Trim().IndexOf(" ") + 1);
                            string strRowPos = strLst[1].Trim().Substring(strLst[1].Trim().IndexOf(" ") + 1);
                            //ColmPos delete .
                            string strColmPos = strLst[2].Trim().Substring(strLst[2].Trim().IndexOf(" ") + 1);
                            strColmPos = strColmPos.TrimEnd('.');

                            strTrueError = "输入的内容不符合Json语法，请确认: " + "\r\n错误关键字：" + strKeyName + "\r\n错误行号：" + strRowPos + "\r\n错误列号：" + strColmPos;

                            System.Windows.MessageBox.Show(strTrueError, "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                            return;
                        }
                    }
                    break;
                case "RemoveAll":
                    eventLogList.Clear();
                    eventLogs.Clear();
                    break;
                case "ExportToExcel":
                    {
                        int nIndex = 0;
                        DataTable dataTable_rsrp = new DataTable("EventLogList");
                        dataTable_rsrp.Columns.Add(new DataColumn("LogID", typeof(string)));
                        dataTable_rsrp.Columns.Add(new DataColumn("Time", typeof(string)));
                        dataTable_rsrp.Columns.Add(new DataColumn("TimeFlag", typeof(string)));
                        dataTable_rsrp.Columns.Add(new DataColumn("EventID", typeof(string)));
                        dataTable_rsrp.Columns.Add(new DataColumn("EventIDInfo", typeof(string)));
                        dataTable_rsrp.Columns.Add(new DataColumn("EventParamInfo", typeof(string)));                        
                        //dataTable_rsrp.Columns.Add(new DataColumn("EventType", typeof(string)));
                        dataTable_rsrp.Columns.Add(new DataColumn("OriData", typeof(string)));
                        dataTable_rsrp.Columns.Add(new DataColumn("HexData", typeof(string)));
                        dataTable_rsrp.Columns.Add(new DataColumn("EventData", typeof(string)));

                        //将解析到的EventLog导出到Excel
                        foreach(EventLog eventLog in eventLogs)
                        {
                            /*
                             * 
                             * string strPredictTime = "[预估]";
                                if(eventLog.bPredictTime == false)
                                    strPredictTime = "[可信]";

                                strPredictTime += (" LogID[" + eventLog.usLogID.ToString() + "]");
                                strPredictTime += (" EventID[" + eventLog.byEventID.ToString() + "]");
            
                                string strDateAndTime = "20" + eventLog.strDate + string.Format(" {0}:{1}:{2}", eventLog.byHour, eventLog.byMin, eventLog.bySecond);
                                string strInfo = "{" + eventLog.strOriLogData + " -> " + eventLog.strHexOriLogData + "}\r\n" + eventLog.strAnalyData + "\r\n" + eventLog.strEventParamInfo;
                                eventLogList.Add(new Tuple<int, string, string>(
                                    (Int32)eventLog.eventType, 
                                    "[" + (eventLogList.Count + 1).ToString() + "] " + strDateAndTime + strPredictTime + " 事件--[" + eventLog.strEventIDInfo + "]", 
                                    strInfo));
                             * 
                             * */ 

                            //string strName = tbTotalName.Text + strIndex;
                            string strDateAndTime = "20" + eventLog.strDate + string.Format(" {0}:{1}:{2}", eventLog.byHour, eventLog.byMin, eventLog.bySecond);
                            string strPredictTime = "[预估]";
                            if (eventLog.bPredictTime == false)
                                strPredictTime = "[可信]";
 
                            dataTable_rsrp.Rows.Add(
                                eventLog.usLogID.ToString(),
                                strDateAndTime,
                                strPredictTime,  
                                eventLog.byEventID.ToString(),                                
                                eventLog.strEventIDInfo,
                                eventLog.strEventParamInfo,                                
                                //eventLog.eventType.ToString(),
                                eventLog.strOriLogData,
                                eventLog.strHexOriLogData,
                                eventLog.strAnalyData);

                            nIndex++;                           
                        }

                        GlobalFun.WriteExcel(dataTable_rsrp, @"D:\\Test.xls");
                    }
                    break;
                default:
                    break;
            }
        }

        private void AnalysisWifiLogs(string strLogs)
        {
            //string strSerializeJSON = System.IO.File.ReadAllText(@"D:\查询日志.txt", Encoding.UTF8);
            //EventLog dataBind = (EventLog)Newtonsoft.Json.JsonConvert.DeserializeObject(strSerializeJSON, typeof(EventLog));

            string strAllText = strLogs;
            //拆分
            string[] condition = { "ED ED " };
            //如果在拆分时不需要包含空字符串，则可以使用 StringSplitOptions.RemoveEmptyEntries 选项，例如在上例中将 StringSplitOptions.None 更改成 StringSplitOptions.RemoveEmptyEntries
            //string[] result = str.Split(condition, StringSplitOptions.None);

            string[] strJSonArray = strAllText.Split(condition, StringSplitOptions.None);
            //try
            {
                GlobalFun.TaskRun(() =>
                {
                    foreach (string strJson in strJSonArray)
                    {
                        int nStartIndex = strJson.IndexOf("{");
                        if (nStartIndex < 0)
                            continue;
                        //提取出IP信息
                        string strIP = strJson.Substring(0, strJson.IndexOf("BE BE BE BE"));
                        strIP = strIP.Substring(strIP.IndexOf("["));
                        //获取到纯JSon数据
                        string strJsonTemp = strJson.Substring(nStartIndex);
                        try
                        {
                            JObject jObj = JObject.Parse(strJsonTemp);
                            //除去多余无效\r\n以及空格
                            //strContentData = jObj.ToString();
                            //strJsonTemp = jObj.ToString().Replace("\r\n ", "");
                            //strJsonTemp = strJsonTemp.Replace("  ", "");
                            //System.Diagnostics.Debug.WriteLine(strJsonTemp);

                            //构建Log
                            List<EventLog> eventLogsLocal = EventLogManager.MakeEventLog(jObj);
                            if (eventLogsLocal == null)
                                continue;
                            foreach (EventLog eventLog in eventLogsLocal)
                            {
                                //增加节点
                                //AddNewItemByEventLog(eventLog);
                                //this.Dispatcher.Invoke()

                                //反查Imei
                                eventLog.strImei = strIP;
                                //eventLog.strLogIP = strIP;
                                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new DelAddNewItemByEventLog(AddNewItemByEventLog), eventLog);

                                Thread.Sleep(4);
                            }
                            //Thread.Sleep(33);
                            //若eventLogList 元素数量已经超过100个了，则开启定时器去继续读取，界面刷新及时些
                        }
                        catch (Newtonsoft.Json.JsonReaderException jsonEx)
                        {
                            string strError = jsonEx.Message;
                            //提取出有效信息，格式化为中文描述
                            string strTrueError = strError.Substring(strError.IndexOf("Path "));
                            string[] strLst = strTrueError.Split(',');

                            string strKeyName = strLst[0].Trim().Substring(strLst[0].Trim().IndexOf(" ") + 1);
                            string strRowPos = strLst[1].Trim().Substring(strLst[1].Trim().IndexOf(" ") + 1);
                            //ColmPos delete .
                            string strColmPos = strLst[2].Trim().Substring(strLst[2].Trim().IndexOf(" ") + 1);
                            strColmPos = strColmPos.TrimEnd('.');

                            strTrueError = "输入的内容不符合Json语法，请确认: " + "\r\n错误关键字：" + strKeyName + "\r\n错误行号：" + strRowPos + "\r\n错误列号：" + strColmPos;

                            System.Windows.MessageBox.Show(strTrueError, "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                            continue;
                        }
                    }
                }
                );
            }
            //catch (Newtonsoft.Json.JsonReaderException jsonEx)
            //{
            //    string strError = jsonEx.Message;
            //    //提取出有效信息，格式化为中文描述
            //    string strTrueError = strError.Substring(strError.IndexOf("Path "));
            //    string[] strLst = strTrueError.Split(',');

            //    string strKeyName = strLst[0].Trim().Substring(strLst[0].Trim().IndexOf(" ") + 1);
            //    string strRowPos = strLst[1].Trim().Substring(strLst[1].Trim().IndexOf(" ") + 1);
            //    //ColmPos delete .
            //    string strColmPos = strLst[2].Trim().Substring(strLst[2].Trim().IndexOf(" ") + 1);
            //    strColmPos = strColmPos.TrimEnd('.');

            //    strTrueError = "输入的内容不符合Json语法，请确认: " + "\r\n错误关键字：" + strKeyName + "\r\n错误行号：" + strRowPos + "\r\n错误列号：" + strColmPos;

            //    System.Windows.MessageBox.Show(strTrueError, "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            //    return;
            //}
        }

        private void AnalysisZKLogs(List<ExcelSheet> excelSheetList)
        {
            //string strAllText = strLogs;
            //拆分
            //string[] condition = { "ED ED " };
            //如果在拆分时不需要包含空字符串，则可以使用 StringSplitOptions.RemoveEmptyEntries 选项，例如在上例中将 StringSplitOptions.None 更改成 StringSplitOptions.RemoveEmptyEntries
            //string[] result = str.Split(condition, StringSplitOptions.None);

            //string[] strJSonArray = strAllText.Split(condition, StringSplitOptions.None);
            //try
            {
                string strHeadFixed = "\"content\":";
                GlobalFun.TaskRun(() =>
                {
                    foreach (ExcelSheet excelSheet in excelSheetList)
                    {
                        foreach(DataRow dataRow in excelSheet.dataTable.Rows)
                        {
                            string strJson = dataRow["^内容"].ToString();

                            int nStartIndex = strJson.IndexOf(strHeadFixed);
                            //if (nStartIndex < 0)
                            //    continue;
                            ////提取出IP信息
                            //string strIP = strJson.Substring(0, strJson.IndexOf("BE BE BE BE"));
                            //strIP = strIP.Substring(strIP.IndexOf("["));
                            //获取到纯JSon数据
                            string strJsonTemp = strJson.Substring(nStartIndex);
                            strJsonTemp = strJsonTemp.Replace(strHeadFixed, "");
                            try
                            {
                                JObject jObj = JObject.Parse(strJsonTemp);
                                //除去多余无效\r\n以及空格
                                //strContentData = jObj.ToString();
                                //strJsonTemp = jObj.ToString().Replace("\r\n ", "");
                                //strJsonTemp = strJsonTemp.Replace("  ", "");
                                //System.Diagnostics.Debug.WriteLine(strJsonTemp);

                                //JToken jtLog = jObj.SelectToken("content");

                                //构建Log
                                List<EventLog> eventLogsLocal = EventLogManager.MakeEventLog(jObj);
                                if (eventLogsLocal == null)
                                    continue;
                                foreach (EventLog eventLog in eventLogsLocal)
                                {
                                    //增加节点
                                    //AddNewItemByEventLog(eventLog);
                                    //this.Dispatcher.Invoke()

                                    //反查Imei
                                    eventLog.strImei = excelSheet.strSheetName;
                                    //eventLog.strLogIP = strIP;
                                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new DelAddNewItemByEventLog(AddNewItemByEventLog), eventLog);

                                    Thread.Sleep(4);
                                }
                                //Thread.Sleep(33);
                                //若eventLogList 元素数量已经超过100个了，则开启定时器去继续读取，界面刷新及时些
                            }
                            catch (Newtonsoft.Json.JsonReaderException jsonEx)
                            {
                                string strError = jsonEx.Message;
                                //提取出有效信息，格式化为中文描述
                                string strTrueError = strError.Substring(strError.IndexOf("Path "));
                                string[] strLst = strTrueError.Split(',');

                                string strKeyName = strLst[0].Trim().Substring(strLst[0].Trim().IndexOf(" ") + 1);
                                string strRowPos = strLst[1].Trim().Substring(strLst[1].Trim().IndexOf(" ") + 1);
                                //ColmPos delete .
                                string strColmPos = strLst[2].Trim().Substring(strLst[2].Trim().IndexOf(" ") + 1);
                                strColmPos = strColmPos.TrimEnd('.');

                                strTrueError = "输入的内容不符合Json语法，请确认: " + "\r\n错误关键字：" + strKeyName + "\r\n错误行号：" + strRowPos + "\r\n错误列号：" + strColmPos;

                                System.Windows.MessageBox.Show(strTrueError, "错误", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                                continue;
                            }
                        }                        
                    }
                }
                );
            }            
        }
    }
}
